package com.gking.resourcePool.interceptor;


import com.gking.resourcePool.common.BaseContext;
import com.gking.resourcePool.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * 拦截请求响应，获取返回状态码和响应信息
 */
@Slf4j
//@ControllerAdvice
public class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 判断该拦截器是否支持对应的控制器方法返回类型
        return true; // 对所有控制器方法都应用该拦截器
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends org.springframework.http.converter.HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 在响应体写入到输出流之前调用此方法

        // 在这里可以访问和修改响应体
        if (body instanceof ResponseEntity) {
            // 如果响应体是 ResponseEntity 类型，可以解包以获取实际的响应体内容
            ResponseEntity<?> responseEntity = (ResponseEntity<?>) body;
            Object responseBody = responseEntity.getBody();
            log.info("Response responseBody: {}", responseBody);
            // 根据需要对 responseBody 进行修改
        } else {
            // 如果响应体不是 ResponseEntity，它就代表控制器方法实际返回的响应体内容
            // 可以直接对 'body' 进行修改

            try {
                Result<Object> result = (Result<Object>) body;
                BaseContext.setResponseCode(result.getCode());
                BaseContext.setResponseMessage(result.getMessage());
            } catch (Exception e) {
                log.info("远程请求，返回体为字符串");
            }

            //  List<String> cookies = response.getHeaders().get("Set-Cookie");
        }

        // 返回修改后（或原始的）响应体内容
        return body;
    }


}
